<template>
  <div class="department-container">
    <div class="app-container">

      <PageTools>
        <!-- <template #left> -->
        <template slot="left">
          总记录数：20条
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto"> -->
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <!-- <el-button type="text" size="small" @click="$router.push('/employees/detail-id/'+scope.row.id)">查看-动态路由参数</el-button> -->
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!--
                分页组件
                total: 总的数据条数
                page-size: 每页显示几条
                @current-change:点击页面触发，它会自动传入当前的页码

              -->
          <el-pagination
            :page-size="pageParams.size"
            layout="prev,pager,next"
            :total="total"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>

    <el-dialog
      title="新增员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <addor-edit
        ref="refAdd"
        @update-empolyee="hUpdateEmpolyee"
        @close="showDialog=false"
      />
    </el-dialog>

    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <!-- v-if="showDialogRole" -->
      <assign-role
        v-if="showDialogRole"
        ref="assignRole"
        :employee-id="curEmployeId"
        @update-close="hUpdateClose"
        @close="showDialogRole=false"
      />
    </el-dialog>

  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog'
import AssignRole from './assignRole.vue'
console.log('EmployeeEnum', EmployeeEnum)

const hireType = { }
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
console.log('hireType', hireType)
// const obj = {
//   1: '正式',
//   2: '非正式'
// }

export default {
  components: {
    'addor-edit': EmpDialog,
    AssignRole
  },
  data() {
    return {
      list: [],
      total: 0,
      pageParams: {
        size: 5,
        page: 1
      },
      curEmployeId: '', // 当前要分配角色的员工id
      showDialogRole: false, // 是否显示分配角色弹层
      showDialog: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')

        // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.list.length === 1) {
          this.pageParams.page--

          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
          // this.pageParams.page = Math.max(--this.pageParams.page, 1)
        }

        // this.roles.length === 1 && (this.pageParams.page = Math.max(--this.pageParams.page, 1))

        // 3. 重新请求
        this.loadEmployeeList()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      console.log('要删除的id', id)
      this.$confirm('此操作将永久删除员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 做删除
        this.doDel(id)
      }).catch(() => {

      })
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log(res)
        const { rows, total } = res.data
        this.list = rows
        this.total = total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // id --> value
    // [{id: 1,value: '正式'},{id: 2,value: '非正式'}]

    // {
    //   1: '正式'
    //   2: '非正式'
    // }
    formatEmployment(id) {
      return hireType[id]
      // console.log('formatEmployment.....', id)
      // const type = EmployeeEnum.hireType.find(item => item.id === id)
      // return type.value
    },
    // 用户点击了页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false

      this.loadEmployeeList()
    },
    // 弹层隐藏了
    hClose() {
      // 重置子组件中的表单
      // this.$refs.子组件.方法（）
      this.$refs.refAdd.resetForm()
    },
    // 导出excel
    async hExportExcel() {
      // 1. 获取数据
      const res = await getEmployeeList(this.pageParams)
      console.log('有效数据:', res.data.rows)
      // 2. 处理数据
      const obj = this.transData(res.data.rows)
      // 3. 导出
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: obj.header, // ['姓名', '工资'], // 表头 必填
          data: obj.data, // [
          //   ['刘备', 800],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'employee-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 写代码
      // header => ['id', '手机号', '用户名', ... ]
      // data => [
      //   ["604f764971f93f3ac8f365c2", "13800000002", "管理员",.... ]
      // ]
      const enKeys = Object.keys(rows[0])
      // const header = enKeys.map(enKey => {
      //   return map[enKey]
      // })

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => Object.values(obj))

      return { header, data }
    },
    // 用户点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true

      this.curEmployeId = id
      console.log('父组件', this.curEmployeId)
      // this.$nextTick
      // 直接找到子组件，调用方法去获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    },
    // 用户分配角色成功
    hUpdateClose() {
      this.showDialogRole = false
      this.loadEmployeeList()
    }
  }
}
</script>
